1.2 Variables in C
Module 1.2 • Fundamentals of Variables, Expressions & Statements
A variable is a named memory location used to store data in a program. It acts like a container that holds information which can be used and modified during program execution.
Every variable is associated with a data type. The data type determines:
- What kind of data can be stored.
- How much memory is allocated.
- The range of values that can be stored.
For example, a variable can store:
- Whole numbers (int)
- Decimal numbers (float, double)
- Single characters (char)
A variable can hold only one value at a time, but its value can be changed whenever required.
Why Do We Use Variables?
Variables help programmers:
- Store user input.
- Perform calculations.
- Save intermediate results.
- Manage program data efficiently.
Example
int score = 95;
Here, the variable score stores the value 95.
1.2.1 Declaring Variables
Before using a variable, it must be declared. Declaration informs the compiler about the variable's name and the type of data it will store.
Syntax
datatype variable_name;
Examples
int quantity;
float temperature;
char section;
double distance;
In the above declarations:
quantitystores integer values.temperaturestores decimal values.sectionstores a single character.distancestores high-precision decimal values.
Declaring Multiple Variables
Several variables of the same type can be declared together.
int physics, chemistry, maths, total;
All four variables are of type int.
1.2.2 Variable Initialization
When a variable is declared without assigning a value, it may contain an unpredictable value known as a garbage value.
To avoid this, variables should be initialized whenever possible.
Syntax
datatype variable_name = value;
Examples
int rollNo = 101;
float height = 172.5;
char gender = 'M';
double taxRate = 0.18;
Multiple variables can also be initialized together.
int a = 10, b = 20, c = 30;
Example:
int x, y, z, sum = 0;
Only sum is initialized. The variables x, y, and z still contain garbage values.
Naming Rules for Variables
A variable name must follow these rules:
Valid Rules
- Must begin with a letter or underscore (_).
- Can contain letters, digits, and underscores.
- Cannot contain spaces.
- Cannot start with a digit.
- Cannot use C keywords.
Valid Variable Names
studentName
_age
totalMarks
price2025
Invalid Variable Names
2marks // Starts with a digit
student name // Contains space
float // Reserved keyword
Case Sensitivity
C is a case-sensitive language.
int count = 10;
int Count = 20;
Here count and Count are treated as two different variables.
Common Data Types in C
| Data Type | Purpose | Example |
|---|---|---|
int | Stores whole numbers | 50 |
float | Stores decimal numbers | 12.75 |
double | Stores large decimal numbers with higher precision | 3.141592653 shift |
char | Stores a single character | 'A' |
Example Program Using Variables
#include <stdio.h>
int main()
{
int employeeId = 501;
float monthlySalary = 38500.75;
double accountBalance = 125000.987654;
char grade = 'B';
printf("Employee ID: %d\n", employeeId);
printf("Monthly Salary: %.2f\n", monthlySalary);
printf("Account Balance: %.6lf\n", accountBalance);
printf("Performance Grade: %c\n", grade);
return 0;
}
Output
Employee ID: 501
Monthly Salary: 38500.75
Account Balance: 125000.987654
Performance Grade: B
1.2.3. Types of Variables in C
Variables can be classified based on where and how they are declared.
1. Local Variables
Local variables are declared inside a function or block. They can only be used within that function or block.
Example
void display()
{
int marks = 80;
printf("%d", marks);
}
The variable marks can only be accessed inside the display() function.
Features
- Created when the function starts.
- Destroyed when the function ends.
- Not accessible outside the function.
2. Global Variables
Global variables are declared outside all functions. They can be accessed by any function in the program.
Example
#include <stdio.h>
int companyCode = 1234;
void showCode()
{
printf("%d", companyCode);
}
Features
- Accessible throughout the program.
- Exists until program execution ends.
3. Static Variables
Static variables retain their value between function calls. They are initialized only once.
Example
#include <stdio.h>
void counter()
{
static int visits = 0;
visits++;
printf("Visits = %d\n", visits);
}
Output after three function calls:
Visits = 1
Visits = 2
Visits = 3
Features
- Value is preserved.
- Initialized only once.
- Exists throughout program execution.
4. Constant Variables
Constant variables are declared using the const keyword. Their value cannot be modified after initialization.
Example
const float GST = 18.0;
Attempting to change the value later will produce a compilation error.
GST = 20.0; // Invalid
Advantages
- Prevents accidental modification.
- Improves program reliability.
1.2.4. Expressions
An expression is a combination of variables, constants, operators, and function calls that produces a result.
Examples
a + b
price * quantity
salary > 50000
age >= 18
status && verified
calculateTotal(amount)
Types of Expressions
Arithmetic Expression
total = price * quantity;
Relational Expression
marks >= 35
Logical Expression
age >= 18 && citizen == 1
Function Call Expression
calculateArea(length, width);
1.2.5. Statements
A statement is an instruction that tells the computer to perform a specific task. Statements are the building blocks of a C program.
Categories of Statements
- Expression Statements
- Compound Statements
- Selection Statements
- Iteration Statements
- Jump Statements
- Label Statements
1.2.6 Expression Statements
An expression followed by a semicolon (;) forms an expression statement.
Examples
total = amount + tax;
counter++;
displayResult();
Null Statement
A statement containing only a semicolon is called a null statement.
;
It performs no action.
1.2.7 Compound Statements
A compound statement is a group of statements enclosed within curly braces { }. It is also known as a block.
Example
{
int length = 6;
int width = 4;
int area;
area = length * width;
printf("Area = %d", area);
}
Important Notes
- No semicolon is required after the closing brace.
- Variables declared inside a block are local to that block.
- They cannot be accessed outside the block.
1.2.8 Comments
Comments are explanatory notes written inside a program to improve readability and understanding. Comments are ignored by the compiler and do not affect program execution.
Single-Line Comment
/* Variable stores monthly salary */
Multi-Line Comment
/*
Program to calculate
student percentage
*/
Benefits of Comments
Comments help to:
- Explain program logic.
- Improve readability.
- Make maintenance easier.
- Assist other programmers in understanding the code.
Important Rules for Comments
- Comments can be written almost anywhere in a program.
- They are ignored during compilation.
- Comments should not be placed inside string or character literals.
- Nested comments are not allowed.
Invalid Example
/* Main Comment
/* Inner Comment */
*/
The above code is incorrect because C does not support comments inside another comment.
Summary
- Variables are named memory locations used to store data.
- Every variable must have a data type.
- Variables should be declared before use.
- Initialization assigns a starting value to a variable.
- C supports local, global, static, and constant variables.
- Expressions combine variables, constants, and operators to produce results.
- Statements are executable instructions in a program.
- Comments improve readability and documentation without affecting execution.
Click your choice for each question to view feedback immediately. Complete all questions to evaluate your metric score.